#include "clonecommand.h"
#include "document.h"

namespace SymbolEditor
{

    CloneCommand::CloneCommand(UndoCommand *parent):
        UndoCommand(parent)
    {

    }

    void CloneCommand::undo()
    {
        for (quint64 id : cloneIdList)
        {
            auto clone = document()->item(id);
            if (clone == nullptr)
            {
                warnItemNotFound("Clone", id);
                continue;
            }
            document()->removeItem(id);
        }
    }

    void CloneCommand::redo()
    {
        if (cloneIdList.isEmpty())
        {
            cloneIdList.reserve(itemIdList.count());
            for (int i = 0; i < itemIdList.count(); i++)
            {
                cloneIdList << 0;
            }
        }

        for (int i = 0; i < itemIdList.count(); i++)
        {
            auto id = itemIdList.value(i);
            auto cloneId = cloneIdList.value(i);
            auto item = document()->item(id);
            cloneId = document()->cloneItem(id, cloneId);
            auto newPosition = item->position() + translation;
            document()->setItemProperty(cloneId, PositionProperty, newPosition);
            cloneIdList.replace(i, cloneId);
        }

        setText(QString("Clone %1 item").arg(itemIdList.count()));
        if (itemIdList.count() > 1)
        {
            setText(text() + "s");
        }
    }

}
